import math
from datetime import datetime, timedelta

from flask import Blueprint, render_template, request, jsonify
from models.my_model import Post, Like, db, User, Comment
from sqlalchemy import func, label, case

from flask_login import login_user, logout_user, current_user, AnonymousUserMixin, \
    login_required  # q80：此处引入了当前登录对象 current_user

from view.data_view import get_today_n_hot_title_split

page_index = Blueprint("page_index", __name__)


@page_index.route("/")
@page_index.route("/index")
def index():
    pageSize = 5
    order_mode: str = request.values.get('orderMode', default=0)
    page = request.values.get('page', default=1)
    page = int(page) if str(page).isdigit() else 1
    order_mode = int(order_mode) if str(page).isdigit() else 0
    cu = User(id=0, type=1) if current_user.is_anonymous else current_user
    # 按点赞数量降序排序
    post_count = Post.query.count()
    post_all = Post.query.order_by(Post.create_time.desc()).paginate(page=page, per_page=pageSize)
    if order_mode == 1:
        post_all = Post.query.order_by(Post.like_count.desc()).paginate(page=page, per_page=pageSize)
        print(post_all)
    # 将帖子id与用户名、头像、用户点赞情况添加如帖子中
    for post in post_all:
        like = Like.query.filter(Like.user_id == cu.id, Like.target_post_id == post.id).first()
        post.like = 0
        if like:
            post.like = 1
        user: User = User.query.filter(User.id == post.user_id).first()
        post.username = user.username
        post.header_url = user.header_url

    # 活跃计算
    tdy_post: int = Post.query.filter(
        db.cast(Post.create_time, db.DATE) == db.cast(datetime.now(), db.DATE)
    ).count()
    tdy_comment: int = Comment.query.filter(
        db.cast(Comment.create_time, db.DATE) == db.cast(datetime.now(), db.DATE)
    ).count()
    tdy_active: int = tdy_post + tdy_comment
    # 活跃计算end

    # 今日热词
    tdy_hot: str = None
    try:
        tdy_hot: str = get_today_n_hot_title_split(1)[0]  # 获取今天的n个热词
    except Exception as e:
        print(e)
    # 今日热词end

    # 置顶帖
    posts_pin = None
    if page == 1: # 仅在第一页渲染置顶帖
        posts_pin: list = Post.query.filter(Post.type == 1).all()
        # 将帖子id与用户名、头像、用户点赞情况添加如帖子中
        for post in posts_pin:
            like = Like.query.filter(Like.user_id == cu.id, Like.target_post_id == post.id).first()
            post.like = 0
            if like:
                post.like = 1
            user: User = User.query.filter(User.id == post.user_id).first()
            post.username = user.username
            post.header_url = user.header_url
    # 置顶帖end
    
    # 推荐帖
    # 近7天内发布，并被加精的帖子
    post_recommend = None
    if page == 1: # 仅在第一页渲染推荐帖
        NOW = datetime.now()
        post_recommend: list = (
            Post.query
            .filter(Post.create_time >= NOW - timedelta(days=7))
            .filter(Post.status == 1)
            .all()
        )
        # 将帖子id与用户名、头像、用户点赞情况添加如帖子中
        for post in post_recommend:
            like = Like.query.filter(Like.user_id == cu.id, Like.target_post_id == post.id).first()
            post.like = 0
            if like:
                post.like = 1
            user: User = User.query.filter(User.id == post.user_id).first()
            post.username = user.username
            post.header_url = user.header_url
    # 推荐帖end

    return render_template(
        "index.html",
        order_mode=order_mode,
        post_count=post_count,
        post_all=post_all,
        tdy_active=tdy_active,
        pagination=post_all,
        tdy_hot=tdy_hot,
        posts_pin=posts_pin,
        post_recommend=post_recommend
    )
